package pro.softzhang.algo.lc1300;

import pro.softzhang.algo.flag.knowledge.KBitManipulation;

/**
 * https://leetcode.cn/problems/minimum-flips-to-make-a-or-b-equal-to-c/solution/huo-yun-suan-de-zui-xiao-fan-zhuan-ci-shu-by-lee-2/
 */
@KBitManipulation
public class LC1318_MinimumFlipsToMakeAorBEqualToC {
    public static void main(String[] args) {
        System.out.println(new Solution().minFlips(8, 3, 5));
    }

    /**
     * 未调通
     */
    static
    class Solution {
        public int minFlips(int a, int b, int c) {
            String abits = Integer.toBinaryString(a), bbits = Integer.toBinaryString(b), cbits = Integer.toBinaryString(c);
            int max = a >= b
                    ? (a >= c ? abits.length() - 1 : cbits.length() - 1)
                    : (b >= c ? bbits.length() - 1 : cbits.length() - 1);
            int min = 0;
            for (int i = 0; i <= max; i++) {
                /**
                 *  1000
                 *    11
                 *   101
                 */
                char ach = abits.length() < i + 1 ? '0' : abits.charAt(abits.length() - i - 1);
                char bch = bbits.length() < i + 1 ? '0' : bbits.charAt(bbits.length() - i - 1);
                char cch = cbits.length() < i + 1 ? '0' : cbits.charAt(cbits.length() - i - 1);
                if(cch == '0') {
                    if (ach == '1' && bch == '1') {
                        min += 2;
                    } else if ((ach == '0' || bch == '1') || (ach == '1' || bch == '0')) {
                        min++;
                    }
                } else { // == '1'
                    if (ach == '0' && bch == '0') {
                        min++;
                    }
                }
            }
            return min;
        }
    }

    static
    class Solution1 {
        public int minFlips(int a, int b, int c) {
            int ans = 0;
            for (int i = 0; i < 31; ++i) {
                int bit_a = (a >> i) & 1;
                int bit_b = (b >> i) & 1;
                int bit_c = (c >> i) & 1;
                if (bit_c == 0) {
                    ans += bit_a + bit_b;
                }
                else {
                    ans += (bit_a | bit_b) ^ 1;
                }
            }
            return ans;
        }
    }
}
